<template>
	<view class="bg-loading bg-white" v-if="showLoading">
		<image class="gif-white response" src="/static/icon/loading-white.gif" mode="aspectFit"></image>
	</view>
	<view v-else>
		<!-- 轮播图 -->
		<swiper-items :swiperItems="goodsDetail.slider_images"></swiper-items>

		<view class="padding bg-white">
			<view class="text-xl text-bold ">{{goodsDetail.goods_name}}</view>
			<view class="flex justify-between align-end padding-tb-sm">
				<view class="">
					<text class="text-price text-xxl text-red text-bold">{{goods_price}}</text>
					<!-- <text class="text-price text-bold text-lg padding-left-sm">{{goodsDetail.vip_price}}</text> -->
					<!-- <image class="vip-image margin-left-xs" src="../../static/vip.png" mode=""></image> -->
				</view>
				<view class="text-xl" @tap="showBottomModal" data-target="ShareModal"><text class="cuIcon-share"></text></view>
			</view>
			<view class="flex justify-between text-gray text-sm">
				<text class="">原价:￥{{line_price}}</text>
				<text>库存:{{stock_num}}{{goodsDetail.unit_name}}</text>
				<text>销量:{{goodsDetail.goods_sales}}</text>
			</view>
		</view>

		<view class="cu-list menu solid-top">
			<view class="cu-item">
				<view class="content padding-tb-sm" @tap="showBottomModal" data-target="CouponModal">
					<text class="text-gray">优惠券:</text><text class="padding-left-sm">满400减30</text>
				</view>
				<view class="action">
					<text class="cuIcon-right"></text>
				</view>
			</view>

			<view class="cu-item margin-top-sm">
				<view class="content padding-tb-sm" @tap="showBottomModal" data-target="TypeModal">
					<text class="text-gray">已选择:</text><text class="padding-left-sm">已选择这个型号</text>
				</view>
				<view class="action">
					<text class="cuIcon-right"></text>
				</view>
			</view>
			<!-- 用户评价 -->
			<view class="cu-item margin-top-sm">
				<view class="content padding-tb-sm">
					<text class="text-lg">用户评价(99+)</text>
				</view>
				<navigator url="comment">
					<view class="action">
						98% 的好评率 <text class="cuIcon-right"></text>
					</view>
				</navigator>
			</view>

			<view class="bg-white padding">
				<view class="flex align-center">
					<view class="cu-avatar round" style="background-image: url(https://ossweb-img.qq.com/images/lol/img/champion/Taric.png);"></view>
					<text class="padding-lr-sm">名字名字名字</text>
					<uni-rate value="3.8" size="14" active-color="#e54d42" :disabled="true"></uni-rate>
				</view>
				<view>
					<view class="padding-tb-sm text-gray">2019-10-14 14:38:7 <text class="padding-left-xs">买了什么型号</text></view>
					<view class="">评论内容评论内容评论内容评论内容评论内容评论内容评论内容评论内容</view>
				</view>
			</view>
			<!-- 产品详情 -->
			<view class="cu-bar bg-white margin-top-sm">
				<view class="content">产品介绍</view>
			</view>
			<parser :html="goodsDetail.content" img-mode="widthFix" lazy-load="true" :show-with-animation="true" :tag-style="imgStyle"></parser>
			<view class="cu-tabbar-height"></view>
		</view>

		<!-- 分享弹窗 start-->
		<view class="cu-modal bottom-modal" :class="modalName=='ShareModal' ? 'show' : ''" @tap="hideBottomModal">
			<view class="cu-dialog" @tap.stop="">
				<view class="padding-xl">分享弹窗</view>
			</view>
		</view>
		<!-- 分享弹窗 end -->

		<!-- 优惠券弹窗 start-->
		<view class="cu-modal bottom-modal" :class="modalName=='CouponModal' ? 'show' : ''" @tap="hideBottomModal">
			<view class="cu-dialog" @tap.stop="">
				<view class="padding-xl">优惠券弹窗</view>
			</view>
		</view>
		<!-- 优惠券弹窗 end -->

		<!-- 产品规格弹窗 start-->
		<view class="cu-modal bottom-modal" :class="modalName=='TypeModal' ? 'show' : ''" @tap="hideBottomModal">
			<view class="cu-dialog" @tap.stop="">
				<view class="flex padding">
					<view class="content">
						<image class="modal-image radius" :src="baseUrl + goodsDetail.image" mode="aspectFill"></image>
					</view>
					<view class="flex flex-sub flex-direction justify-between padding-left text-left">
						<view class="text-cut text-content"><text class="text-lg">{{goodsDetail.goods_name}}</text></view>
						<view>
							<text class="text-red light text-xl text-price">{{goods_price}}</text>
							<text class="text-gray light padding-left-xs">库存：{{stock_num}}</text>
						</view>
					</view>
					<view class="text-xxl" @tap="hideBottomModal">
						<text class="cuIcon-close text-gray"></text>
					</view>
				</view>

				<!-- 规格信息 -->
				<block v-for="(item,index) in specData.spec_attr" :key="item.group_id">
					<view class="text-gray text-left text-lg padding-left">{{item.group_name}}</view>
					<view class="grid col-5 padding-sm">
						<view class="padding-xs" v-for="(vitem,vindex) in item.spec_items" :key="vitem.item_id">
							<button class="cu-btn block shadow-blur" :class="vitem.checked ? 'bg-red' : 'line-gray'" @tap="ChooseCheckbox"
							 :data-attr-idx="index" :data-item-idx="vindex">{{vitem.spec_value}}</button>
						</view>
					</view>
				</block>

				<view class="text-gray text-left text-lg padding-left">数量</view>
				<view class="text-left padding">
					<uni-number-box @change="bindNumChange" :min="1" :max="stock_num"></uni-number-box>
				</view>

				<view class="cu-bar btn-group">
					<button class="cu-btn bg-orange round shadow-blur" @tap="create(false)">加入购物车</button>
					<button class="cu-btn bg-red round shadow-blur" @tap="create(true)">立即购买</button>
				</view>
			</view>
		</view>
		<!-- 产品规格弹窗 end -->

		<!-- 底部固定 start -->
		<view class="box">
			<view class="cu-bar bg-white tabbar noborder shop foot">
				<button class="action" open-type="contact">
					<view class="cuIcon-service text-green">
						<view class="cu-tag badge"></view>
					</view> 客服
				</button>
				<view class="action" @tap="userCollect">
					<view class="cuIcon-favor"></view>收藏
				</view>
				<navigator url="../cart/index" hover-class="none" open-type="switchTab">
					<view class="action">
						<view class="cuIcon-cart">
							<view class="cu-tag badge">5</view>
						</view>购物车
					</view>
				</navigator>
				<view class="btn-group">
					<button class="cu-btn bg-orange round shadow-blur" @tap="create(false)">加入购物车</button>
					<button class="cu-btn bg-red round shadow-blur" @tap="create(true)">立即购买</button>
				</view>
			</view>
		</view>
		<!-- 底部固定 end -->

		<!-- 授权 -->
		<zhi-authorize :isShow="false" :isAutoLogin="isAutoLogin" ref="isShow"></zhi-authorize>
	</view>
</template>

<script>
	const app = getApp()
	import util from '@/common/util.js'
	import parser from '@/components/jyf-Parser/index.vue'
	import uniRate from '@/components/uni-rate/uni-rate.vue'
	import swiperItems from '@/components/swiper-items/swiper-items.vue'
	import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue'
	import zhiAuthorize from '@/components/zhi-authorize/zhi-authorize.vue'
	export default {
		components: {
			parser,
			uniRate,
			swiperItems,
			uniNumberBox,
			zhiAuthorize
		},
		data() {
			return {
				baseUrl: this.$api.baseUrl,
				modalName: null,
				showLoading: true,
				isAutoLogin: false, // 是否自动登录
				goodsId: 0,
				goodsDetail: [],
				sliderImages: [],
				goods_price: 0, // 商品价格
				line_price: 0, // 划线价格
				stock_num: 0, // 库存数量
				goods_num: 1, // 商品数量
				goods_sku_id: 0, // 规格id
				cart_total_num: 0, // 购物车商品总数量
				specData: {}, // 多规格信息
				goods_spec_arr: [], // 记录多规格的数组
				specSelect: [], // 第1次点击购买的时候弹出规格
				imgStyle: {
					img: 'vertical-align:middle;'
				}
			}
		},
		onLoad(options) {
			// 扫码二维码进入
			if (options.scene) {
				let params = util.getUrlParams(decodeURIComponent(options.scene))
				if (params.id) this.goodsId = params.id; // 商品id
				if (params.spread_id) app.globalData.spread_id = params.spread_id; // 推广人id
			}
			// 普通分享进入
			if (!options.id) util.Toast({ title: '参数错误' }, { tab: 3, url: 1 })
			this.goodsId = options.id
			if (options.spread_id) app.globalData.spread_id = options.spread_id
			
			uni.$on('listenAuthorize', (e) => {
				this.getUserInfo()
			})
			
			this.goodsView(options.id)
		},
		methods: {
			/* 获取商品信息 */
			async goodsView(id) {
				try { // TODO 是否需要绑定上下级关系
					let res = await this.$api.goodsView({id})
					if (res.code === 0) {
						uni.showModal({
							title: res.msg,
							showCancel: false
						})
					}
					let r = res.data.detail
					this.goodsDetail = r
					this.goods_sku_id = r.spec[0].spec_sku_id;
					this.goods_price = r.spec[0].goods_price;
					this.line_price = r.spec[0].line_price;
					this.stock_num = r.spec[0].stock_num;

					if (r.spec_type == 20) {
						this.specData = this.initManySpecData(res.data.specData);
					}
					this.showLoading = false
				} catch (err) {
					util.Toast({ title: err.msg }, { tab:3, url: 1})
				}
				uni.$off('listenAuthorize')
			},
			/* 初始化商品多规格 */
			initManySpecData(data) {
				for (let i in data.spec_attr) {
					for (let j in data.spec_attr[i].spec_items) {
						if (j < 1) {
							data.spec_attr[i].spec_items[0].checked = true;
							this.goods_spec_arr[i] = data.spec_attr[i].spec_items[0].item_id;
						}
					}
				}
				return data;
			},
			/* 选择规格 */
			ChooseCheckbox(e) {
				let attrIdx = e.currentTarget.dataset.attrIdx,
					itemIdx = e.currentTarget.dataset.itemIdx,
					specData = this.specData;
				for (let i in specData.spec_attr) {
					for (let j in specData.spec_attr[i].spec_items) {
						if (attrIdx == i) {
							specData.spec_attr[i].spec_items[j].checked = false;
							if (itemIdx == j) {
								specData.spec_attr[i].spec_items[itemIdx].checked = true;
								this.goods_spec_arr[i] = specData.spec_attr[i].spec_items[itemIdx].item_id;
							}
						}
					}
				}
				this.specData = specData
				// 更新商品规格信息
				this.updateSpecGoods();
			},
			/* 更新商品规格信息 */
			updateSpecGoods() {
				let spec_sku_id = this.goods_spec_arr.join('_');

				// 查找skuItem
				let spec_list = this.specData.spec_list,
					skuItem = spec_list.find((val) => {
						return val.spec_sku_id == spec_sku_id;
					});

				// 记录goods_sku_id
				// 更新商品价格、划线价、库存
				if (typeof skuItem === 'object') {
					this.goods_sku_id = skuItem.spec_sku_id
					this.goods_price = skuItem.form.goods_price
					this.line_price = skuItem.form.line_price
					this.stock_num = skuItem.form.stock_num
				}
			},
			/* 弹窗 */
			showBottomModal(e) {
				if (app.globalData.isLogin) {
					console.log(e);
					let name = e.currentTarget.dataset.target
					this.modalName = name
				} else {
					this.$refs.isShow.isAutoShow = true
					this.isAutoLogin = true
				}
			},
			hideBottomModal(e) {
				this.modalName = null
			},
			/* 数量选择 */
			bindNumChange(value) {
				this.goods_num = value
			},
			/* 收藏商品 */
			async userCollect() {
				try {
					// #ifdef MP
					if (app.globalData.isLogin === false) {
						this.$refs.isShow.isAutoShow = true
					} else {
						let res = await this.$api.userCollect(this.goodsId)
						// TODO another collect action
					}
					// #endif
					// #ifdef H5
					// 前往 h5 登录页
					// #endif
				} catch (e) {
					//TODO handle the exception
				}
			},
			/* 加入购物车或立即购买 */
			create(isBuy) {
				if (app.globalData.isLogin) {
					if (this.specSelect.length == 0) {
						this.specSelect = this.goods_spec_arr
						this.modalName = 'TypeModal'
					} else {
						this.cartCreate(isBuy)
					}
				} else {
					this.$refs.isShow.isAutoShow = true
					this.isAutoLogin = true
				}
			},
			/* 立即购买则加入订单,否则加入购物车 */
			async cartCreate(isBuy) {
				try {
					let res = await this.$api.cartCreate({
						goodsId: this.goodsId,
						goodsNum: this.goods_num, // 默认规格和数量
						goodsSkuId: this.goods_sku_id,
						isBuy: isBuy === true ? 1 : 0
					})
					this.modalName = null
					this.specSelect = []; // 重新初始化临时设定的规格数组
					if (isBuy) {
						uni.navigateTo({
							url: '/pages/order/create?cartId=' + res.data.cartId,
						})
					} else {
						util.Toast({ title: '添加成功', icon: 'success' })
						this.cartCount = res.data.cartCount
					}
				} catch (err) {
					util.Toast({ title: err.msg })
				}
			},
			/* 获取用户信息：购物车数量、优惠券数量 */
			async getUserInfo() {
				try {
					let res = await this.$api.userCommonInfo({ goodsId: this.goodsId })
				} catch (err) {
					util.Toast({ title: err.msg })
				}
				uni.$off('listenAuthorize')
			},
		},
	}
</script>

<style lang="scss">
	.bg-loading {
		position: fixed;
		height: 100%;
		width: 100%;

		image {
			top: 30%; //TODO 此处可以换成其他的方式，不要使用top
		}
	}

	.vip-image {
		width: 46upx;
		height: 22upx;
	}

	.bottom {
		height: 100upx;
	}

	.cu-modal.bottom-modal .cu-dialog {
		border-radius: 20upx 20upx 0 0;

		.text-content {
			width: 480upx;
		}
	}
// TODO统一规范图片的大小
	.modal-image {
		width: 150upx;
		height: 150upx;
	}

	.cu-bar.tabbar.shop .action {
		width: 110upx;
	}
</style>
